layui.use(['upload', 'element', 'form'], function() {
    var $ = layui.jquery
        , upload = layui.upload
        , element = layui.element
        , form = layui.form;

    // 获取个人信息，展示
    $.ajax({
        type: "GET",
        url:"/user/detail/",
        headers:{
          'Authorization': localStorage.getItem('Authorization')
        },
        success:function (msg){
            let code = msg.code;
            let data = msg.data;
            let detail = data.detail;
            let nickname = data.email;
            if(code != 0){ // 请求失败
                location.href = '/static/index.html'
            }else{
              if(detail.nickname){
                  nickname = detail.nickname;
              }
              $('input[name="nickname"]').val(detail.nickname);
              $('input[name="phone"]').val(detail.phone);
              $('input[name="age"]').val(detail.age);
              $('input[name="address"]').val(detail.address);
              $('input[name="birthday"]').val(detail.birthday);
              if(detail.sex == 0){
                  $('input[name="sex"][value="1"]').prop('checked', 'false');
                  $('input[name="sex"][value="0"]').prop('checked', 'true');
              }
              form.render();
            }
            $('#nickname').html(nickname);
            $('#portrait_t').attr('src', detail.portrait);
        }
    })


    // 拖拽上传
    upload.render({
    elem: '#portrait'
    ,url: '/user/portrait/upload/'
    ,headers:{
      'Authorization': localStorage.getItem('Authorization')
    }
    ,done: function(res){
      layer.msg('上传成功');
      console.log(res.data);
      $('#upload-render').removeClass('layui-hide').find('img').attr('src', res.data)
        $('#portrait_t').attr('src', res.data);
    }
  });

  //监听提交
  form.on('submit(info)', function(data){
     $.ajax({
        type: "POST",
        url:"/user/detail/",
        headers:{
          'Authorization': localStorage.getItem('Authorization')
        },
         data:data.field,
        success:function (msg){
            $('#nickname').html($('input[name="nickname"]').val());
        }
     })
    return false;
  });

  //自定义验证规则
  form.verify({
    phone: [/^[1][3-9][0-9]{9}$/, '11位有效手机号']
    ,age: [
      /^([0-9]|[1-9][0-9]|1[0-7][0-9]|180)$/
      ,'年龄必须是数字，且不超过180'
    ]
  });

})